#include <iostream>
#include <thread>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <chrono>
extern "C" {
#include "ring.h"
}

extern int D_x_one;
extern int pic_null;
extern int ripe_flag;
extern int ripe_num;
extern int pass_flag;
extern int cam_start;
extern int car_calibrate_flag;

using namespace cv;
using namespace std;

// 全局变量用于保存物体中心坐标的 x 和 y 分量
int x = 0;
int y = 0;
int col = -1;
int goods= 1;
int max_idx_red = -1;


void* ring_cpp(void* arg) {
        int nangua_green_num;
        
    // 打开摄像头
    VideoCapture cap(0);
    if (!cap.isOpened()) {
        cout << "无法打开摄像头" << endl;
        return NULL;
    }
    

while(1)
{
        if (car_calibrate_flag == 1) {
    Mat frame;
    cap >> frame; // 读取摄像头的帧

    if (frame.empty()) {
        std::cout << "Error: Failed to capture frame." << std::endl;
        break;
    }

    // 转换为灰度图像
    Mat gray;
    cvtColor(frame, gray, COLOR_BGR2GRAY);

    // 二值化
    Mat binary;
    threshold(gray, binary, 200, 255, THRESH_BINARY);

    // 腐蚀和膨胀
    Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5));
    morphologyEx(binary, binary, MORPH_CLOSE, kernel);

    // 查找轮廓
    std::vector<std::vector<Point>> contours;
    findContours(binary, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);

    // 记录距离中心最近的十字索引和距离
    int nearest_index = -1;
    double min_distance = std::numeric_limits<double>::max();

    // 遍历轮廓
    for (size_t i = 0; i < contours.size(); ++i) {
        // 过滤小的轮廓
        if (contourArea(contours[i]) < 100) continue;

        // 拟合轮廓
        RotatedRect rotatedRect = minAreaRect(contours[i]);
        Point2f vertices[4];
        rotatedRect.points(vertices);

        // 计算长宽比
        float aspectRatio = rotatedRect.size.width / rotatedRect.size.height;

        // 判断是否为十字
        if (aspectRatio > 0.5 && aspectRatio < 2.0) {
            // 获取十字中心点坐标
            Point center = rotatedRect.center;

            // 计算十字中心点与图像中心点的距离
            double distance = norm(center - Point(frame.cols / 2, frame.rows / 2));

            // 更新最近距离和索引
            if (distance < min_distance) {
                min_distance = distance;
                nearest_index = i;
            }

            // 绘制矩形框
            Rect boundingRect = rotatedRect.boundingRect();
            rectangle(frame, boundingRect, Scalar(255, 0, 0), 2);
        }
    }

    // 如果找到了最近的十字
    if (nearest_index != -1) {
        // 获取最近的十字中心点坐标
        RotatedRect nearest_rect = minAreaRect(contours[nearest_index]);
        Point nearest_center = nearest_rect.center;

        // 绘制最近的十字
        line(frame, Point(nearest_center.x - 20, nearest_center.y), Point(nearest_center.x + 20, nearest_center.y), Scalar(0, 0, 255), 2);
        line(frame, Point(nearest_center.x, nearest_center.y - 20), Point(nearest_center.x, nearest_center.y + 20), Scalar(0, 0, 255), 2);
        
        // 绘制矩形框的中心点
        circle(frame, nearest_center, 5, Scalar(0, 255, 0), -1);
    }

    // 显示结果
    imshow("Cross Detection", frame);

    // 按下ESC键退出
    if (waitKey(1) == 27) break;
}

       
       
            if(cam_start == 1){
                Mat frame;
                cap >> frame;

                // 转换为HSV颜色空间
                Mat hsv;
                cvtColor(frame, hsv, COLOR_BGR2HSV);

                // 红色范围的HSV阈值
                Scalar lower_red1(0, 50, 50);
                Scalar upper_red1(10, 255, 255);
                Scalar lower_red2(170, 50, 50);
                Scalar upper_red2(180, 255, 255);
                
                // 绿色范围的HSV阈值
                        Scalar lower_green(35, 50, 50);
                        Scalar upper_green(85, 255, 255);
                
                // 对图像进行颜色过滤
                Mat mask_red1, mask_red2, mask_green;
                inRange(hsv, lower_green, upper_green, mask_green);
                inRange(hsv, lower_red1, upper_red1, mask_red1);
                inRange(hsv, lower_red2, upper_red2, mask_red2);

                // 合并红色的两个mask
                Mat mask_red;
                bitwise_or(mask_red1, mask_red2, mask_red);

                // 对过滤后的图像进行形态学操作，去除噪点
                Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5));
                morphologyEx(mask_red, mask_red, MORPH_OPEN, kernel);
                morphologyEx(mask_green, mask_green, MORPH_OPEN, kernel);
                // 查找红色物体的轮廓
                vector<vector<Point>> contours_red,contours_green;
                findContours(mask_green, contours_green, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
                findContours(mask_red, contours_red, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);



                
                // 找到最大的绿色轮廓
                double max_area_green = 0;
                int max_idx_green = -1;
                for (int i = 0; i < contours_green.size(); i++)
                {
                        double area = contourArea(contours_green[i]);
                        if (area > max_area_green)
                        {
                                max_area_green = area;
                                max_idx_green = i;
                        }
                }
                
                // 找到最大的红色轮廓
                double max_area_red = 0;
                
                for (int i = 0; i < contours_red.size(); i++) {
                    double area = contourArea(contours_red[i]);
                    
                    if (area > max_area_red) {

                        max_area_red = area;
                        max_idx_red = i;
                    }
                }
                cout << "红色面积" << max_area_red << endl;
                cout << "绿色面积" << max_area_green << endl;
                
               
                
                if(max_area_red <500 && max_area_green < 500)
                {
                    imshow("Frame", frame);
                    nangua_green_num++;
                    cout<<"绿色计数"<<nangua_green_num<<endl;
                    if(nangua_green_num > 35)
                    {
                            pic_null = 1;
                            std::this_thread::sleep_for(std::chrono::milliseconds(3));
                            nangua_green_num = 0;
                            pass_flag = 1;
                            cam_start = 0;
                            cout<<cam_start<<endl;
                            //~ if(cam_start == 0)
                            //~ {
                                    //~ break;
                                    //~ }
                            }
                    continue;
                }
                cout<<"目标出现"<<endl;
                if(max_area_red > max_area_green)
                {
                        cout << "红色面积ID" << max_idx_red << endl;
                        col = 1;
                    }
                    else{
                        cout << "绿色面积ID" << max_idx_green << endl;
                        col = 0;
                        nangua_green_num++;
                        if(nangua_green_num > 30)
                        {
                            std::this_thread::sleep_for(std::chrono::milliseconds(3));
                            nangua_green_num = 0;
                            pass_flag = 1;
                            cam_start = 0;
                            cout<<cam_start<<endl;
                            //~ if(cam_start == 0)
                            //~ {
                                    //~ break;
                                    //~ }
                        }
                }
                cout<<col<<endl;
                // 如果找到了红色物体
                if(col == 1 )
                {
                        cout<<"red_coming"<<endl;
                        ripe_num ++;           //成熟值计数
                        
                        
                        Moments m = moments(contours_red[max_idx_red]);
                        Point center(m.m10 / m.m00, m.m01 / m.m00);
                    
                        x = center.x;
                        
                        if( x < 400 && x > 200 )
                        {
                            D_x_one = 1;
                            cout << D_x_one << endl;
                            }
                        y = center.y;
                        // 在原图上绘制和中心点
                        circle(frame, center, 5, Scalar(0, 255, 0), -1);
                        cout << "红色物块中心点坐标：" << center << endl;
                        cout << "颜色：红色" << endl;
             
                }
                else if(col == 0 )
                {
                        cout<<"green_coming"<<endl;
                        
                        Moments m = moments(contours_green[max_idx_green]);
                        // 在原图上绘制和中心点
                        Point center(m.m10 / m.m00, m.m01 / m.m00);
                        circle(frame, center, 5, Scalar(0, 0, 255), -1);
                        if( center.x < 400 && center.x > 200 )
                        {
                            D_x_one = 2;
                            cout << D_x_one << endl;
                            }
                        
                        //~ x = center.x;
                        //~ y = center.y;
                        cout << "绿色物块中心点坐标：" << center << endl;
                        cout << "颜色：绿色" << endl;
               
                
                }
                // 显示结果
                if(col == 0 )
                        drawContours(frame, contours_green, max_idx_green, Scalar(0, 255, 0), 2);
                else
                        drawContours(frame, contours_red, max_idx_red, Scalar(0, 0, 255), 2);
                imshow("Frame", frame);

                // 按下ESC键退出程序
                if (waitKey(1) == 27) break;
            }
    
}
    // 释放摄像头
    cap.release();
    destroyAllWindows();

    return NULL;
}
